package com.xiaoyu.lanling.feature.coin.activity

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import com.xiaoyu.base.data.UserData
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity
import com.xiaoyu.lanling.event.coin.CoinIncomeEvent
import com.xiaoyu.lanling.feature.coin.data.CoinData
import com.xiaoyu.lanling.router.Router
import kotlinx.android.synthetic.main.activity_coin_income.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class CoinIncomeActivity : AppCompatToolbarActivity() {

    private val requestTag = Any()

    override fun onCreateSafelyAfterAppFinishInit(savedInstanceState: Bundle?) {
        super.onCreateSafelyAfterAppFinishInit(savedInstanceState)
        setLightStatusBar()
        setContentView(R.layout.activity_coin_income)
        initToolbar()

        initView()
        initBind()
        initEvent()
    }

    override fun onStartSafelyAfterAppFinishInit(isFirstTimeStart: Boolean) {
        super.onStartSafelyAfterAppFinishInit(isFirstTimeStart)
        initData()
    }

    private fun initBind() {
        button.setOnClickDebounceListener {
            Router.instance.gotoCoinExchangeListActivity(this)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_coin_income, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            R.id.record -> {
                val domain = UserData.getInstance().tokenInfo.cookieDomains.optString("lanling")
                Router.instance.goToWebView(this, "https://$domain/pointList.html")
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }


    private fun initView() {
        setTitle(R.string.coin_income_title)
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: CoinIncomeEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                showData(event)
            }
        })
    }

    private fun showData(event: CoinIncomeEvent) {
        balance_desc.text = getString(R.string.coin_income_point_balance_desc, event.pointBalance)
        withdraw_desc.text = getString(R.string.coin_income_point_withdraw_max_desc, event.refundMax)
    }

    private fun initData() {
        CoinData.myPoint(requestTag)
    }
}